﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace Wolfpack.Contrib.Checks.Powershell
{
    public class PipelineResults
    {
        private static readonly PipelineResults _empty = new PipelineResults();

        private readonly List<object> _outputs;
        private readonly Exception _exception;

        /// <summary>
        /// Prevents a default instance of the <see cref="PipelineResults"/> class from being created.
        /// </summary>
        private PipelineResults()
        {
            _outputs = new List<object>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PipelineResults"/> class.
        /// </summary>
        /// <param name="exception">The exception.</param>
        public PipelineResults(Exception exception)
        {
            _outputs = new List<object>();
            _exception = exception;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PipelineResults"/> class.
        /// </summary>
        /// <param name="pipeline">The pipeline.</param>
        /// <param name="output">The output.</param>
        public PipelineResults(Pipeline pipeline, Collection<PSObject> output)
        {
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }
            
            _outputs = GetOutputs(output);
        }

        /// <summary>
        /// Represents empty result set.
        /// </summary>
        public static PipelineResults Empty { get { return _empty; } }

        /// <summary>
        /// Gets the exception.
        /// </summary>
        public Exception Exception
        {
            get { return _exception; }
        }

        /// <summary>
        /// Gets the outputs from the pipeline.
        /// </summary>
        public ReadOnlyCollection<object> Outputs
        {
            get { return _outputs.AsReadOnly(); }
        }

        /// <summary>
        /// Gets the outputs.
        /// </summary>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        private static List<object> GetOutputs(ICollection<PSObject> output)
        {
            List<object> objs = new List<object>(output.Count);

            foreach (PSObject pSObject in output)
            {
                objs.Add(pSObject != null ? pSObject.BaseObject : null);
            }

            return objs;
        }

    }
}